//
//  HFPictureSelectorViewController.swift
//  sinaMicroBlog
//
//  Created by mac on 15/11/20.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let column: CGFloat = 4
private let pictureCellMaigin: CGFloat = 10
class HFPictureSelectorViewController: UICollectionViewController {

    lazy var imageList = [UIImage]()
    
    init() {
        let layout = UICollectionViewFlowLayout()
        //大小,行距.列距,组距
        
        let length = (screenW - (column + 1) * pictureCellMaigin ) / column
        layout.itemSize = CGSizeMake(length, length)
        layout.minimumInteritemSpacing = pictureCellMaigin
        layout.minimumLineSpacing = pictureCellMaigin
        layout.sectionInset = UIEdgeInsets(top: pictureCellMaigin, left: pictureCellMaigin, bottom: 0, right: pictureCellMaigin)
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(HFPictureSelectorViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return imageList.count + 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HFPictureSelectorViewCell
    
        // Configure the cell
        cell.selectorCellDelegate = self
        cell.backgroundColor = UIColor.randomColor()
        if indexPath.item == imageList.count {
            cell.image = nil
        } else {
            cell.image = imageList[indexPath.item]
        }
    
        return cell
    }

}


extension HFPictureSelectorViewController: HFPictureSelectorViewCellDelegate {
    func userWillAddPicture(cell: HFPictureSelectorViewCell) {
        
        if cell.image != nil {
            print("已经添加图片")
            return
        }

        let picker = UIImagePickerController()
        
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
        
    }
    func userWillDeletePicture(cell: HFPictureSelectorViewCell) {
        let indexPath = collectionView?.indexPathForCell(cell)
        self.imageList.removeAtIndex(indexPath!.item)
        
        //刷新视图
        
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            cell.alpha = 0
            }) { (_) -> Void in
                cell.alpha = 1
                self.collectionView?.reloadData()
        }

    }
}

extension HFPictureSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        imageList.append(image)
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}

@objc protocol HFPictureSelectorViewCellDelegate: NSObjectProtocol {
    optional func userWillAddPicture(cell: HFPictureSelectorViewCell)
    optional func userWillDeletePicture(cell: HFPictureSelectorViewCell)
}


class HFPictureSelectorViewCell: UICollectionViewCell {
    
    weak var selectorCellDelegate: HFPictureSelectorViewCellDelegate?
    
    @objc private func addBtnDidClick(){
        selectorCellDelegate?.userWillAddPicture?(self)
    }
    
    @objc private func deleteBtnDidClick() {
        selectorCellDelegate?.userWillDeletePicture?(self)
    }
    
    //图片数据模型
    var image: UIImage? {
        didSet {
            deleteBtn.hidden = (image == nil)
            
            if image != nil {
                addBtn.setBackgroundImage(image, forState: .Normal)
            } else {
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)

            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: UIControlEvents.TouchUpInside)


    }
    
    //懒加载
    private lazy var addBtn: UIButton = UIButton(title: nil, backImage: "compose_pic_add", titleColor: nil)
    private lazy var deleteBtn: UIButton = UIButton(title: nil, backImage: "compose_photo_close", titleColor: nil)
    
}

